package net.NingXiaRuiTai.ShortChain.strategy;

import net.NingXiaRuiTai.ShortChain.enums.BizCodeEnum;
import net.NingXiaRuiTai.ShortChain.exception.BizeException;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;

public class CustomDBPreciseShardingAlgorithm implements PreciseShardingAlgorithm<String> {
    /**
     * @param availableTargetNames 数据源集合
     *                             在分库时值为所有分⽚库的集合 databaseNames
     *                             分表时为对应分⽚库中所有分⽚表的集合 tablesNames
     * @param shardingValue        分⽚属性，包括
     *                             logicTableName 为逻辑表，
     *                             columnName 分⽚健字段），
     *                             value 为从 SQL 中解析出的分⽚健的值
     * @return targetName
     */
    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<String> shardingValue) {
        //获取分库键值(短链码)的第一位，库位
        String substring = shardingValue.getValue().substring(0, 1);
        for (String targetName : availableTargetNames) {
            //获取数据库名最后一位
            String dbLastCharacter = targetName.substring(targetName.length() - 1);

            if (dbLastCharacter.equals(substring)) {
                return targetName;
            }
        }
        throw new BizeException(BizCodeEnum.DB_ROUTE_NOT_FOUND);


    }
}
